package com.astudio.lhasa;

import android.app.Application;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.astudio.lhasa.http.HttpService;
import com.astudio.lhasa.model.DaoMaster;
import com.astudio.lhasa.model.DaoSession;
import com.astudio.lhasa.model.Image;
import com.astudio.lhasa.model.TourSpot;
import com.astudio.lhasa.workers.ai.map.BaseVendorMap;
import com.astudio.lhasa.workers.ai.map.MapLocationManager;
import com.astudio.lhasa.workers.ai.map.vendor.baidu.BaiduVendorBaseVendorMap;
import com.baidu.mapapi.SDKInitializer;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.google.gson.Gson;
import com.iflytek.cloud.SpeechUtility;

import org.litepal.LitePal;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class MyApplication extends Application {
    public static final String DB_NAME = "app.db";

    private static DaoSession mDaoSession;
    private static MyApplication mApplication;

    @Override
    public void onCreate() {
        super.onCreate();
        copyDBToDatabases();
        DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, DB_NAME);
        SQLiteDatabase db = helper.getWritableDatabase();
        DaoMaster daoMaster = new DaoMaster(db);
        mDaoSession = daoMaster.newSession();
        mApplication = this;
        Fresco.initialize(this);
        LitePal.initialize(this);
        SpeechUtility.createUtility(this, "appid=58d8bc04");
        HttpService.init();
        SDKInitializer.initialize(this);
        BaseVendorMap map = new BaiduVendorBaseVendorMap();
        MapLocationManager.getInstance(map).initMap();
        MapLocationManager.getInstance(null).turnOnMap();
        //initData();
    }

    public static DaoSession getDaoSession() {
        return mDaoSession;
    }

    private void initData() {
        Class[] dataSource = {
                DataSourceLasa.class, DataSourceLingzhi.class, DataSourceNamucuo.class
                , DataSourceAli.class, DataSourceRikaze.class
        };
        for (int j = 0; j < dataSource.length; j++) {
            Class clazz = dataSource[j];
            for (int i = 1; i < 15; i++) {
                try {
                    Object o = clazz.newInstance();
                    Field content = clazz.getField("content" + i);
                    Field images = clazz.getField("images" + i);
                    content.setAccessible(true);
                    images.setAccessible(true);
                    String jsonContent = content.get(o).toString();
                    String[] imageUrls = (String[]) images.get(o);
                    Log.d("aifeng", "initData: " + jsonContent);
                    Log.d("aifeng", "initData: " + imageUrls);

                    Gson gson = new Gson();
                    Log.d("aifeng", "initData: " + jsonContent);
                    TourSpot spot = gson.fromJson(jsonContent, TourSpot.class);
                    spot.setCity(j + 1);
                    MyApplication.getDaoSession().getTourSpotDao().insert(spot);
                    Log.d("aifeng", "initData: " + spot);
                    List<Image> imgs = new ArrayList<>(imageUrls.length);
                    for (String url : imageUrls) {
                        Image image = new Image();
                        image.setOwner(spot.getId());
                        image.setUrl(url);
                        imgs.add(image);
                    }
                    MyApplication.getDaoSession().getImageDao().insertInTx(imgs);
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InstantiationException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void copyDBToDatabases() {
        String DB_PATH="/data/data/" + getPackageName() + "/databases/";
        try {
            String outFileName = DB_PATH + DB_NAME;
            File file = new File(DB_PATH);
            if (!file.mkdirs()) {
                file.mkdirs();
            }
            File dataFile = new File(outFileName);
            if (dataFile.exists()) {
                return;
            }
            InputStream myInput;
            myInput = this.getAssets().open(DB_NAME);
            OutputStream myOutput = new FileOutputStream(outFileName);
            byte[] buffer = new byte[1024];
            int length;
            while ((length = myInput.read(buffer)) > 0) {
                myOutput.write(buffer, 0, length);
            }
            myOutput.flush();
            myOutput.close();
            myInput.close();
            Log.d("aifeng", "copy db");
        } catch (IOException e) {
            Log.d("aifeng", "error " + e.toString());
            e.printStackTrace();
        }
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        MapLocationManager.getInstance(null).turnOffMap();
    }

    public static MyApplication getTIApplication() {
        return mApplication;
    }
}
